package com.sumer.psychology.photo.application.command;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.photo.domain.model.Album;
import com.sumer.psychology.photo.domain.model.AlbumId;
import com.sumer.psychology.photo.domain.model.AlbumRepository;
import org.springframework.transaction.annotation.Transactional;

/**
 * 相册服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/29
 * Time: 15:57
 */
@Transactional
public class AlbumApplicationService {
    private AlbumRepository albumRepository;

    public AlbumApplicationService(AlbumRepository albumRepository) {
        this.albumRepository = albumRepository;
    }

    /**
     * 新建相册
     *
     * @param createAlbumCommand command
     */
    public AlbumId newAlbum(CreateAlbumCommand createAlbumCommand) {
        Album anAlbum = new Album(
                albumRepository().nextIdentity(),
                createAlbumCommand.name(),
                createAlbumCommand.description(),
                createAlbumCommand.author());

        albumRepository().add(anAlbum);
        return anAlbum.albumId();
    }

    /**
     * 编辑相册
     *
     * @param changeAlbumCommand command
     */
    public void change(ChangeAlbumCommand changeAlbumCommand) {
        Album anAlbum = albumRepository().ofAlbumId(new AlbumId(changeAlbumCommand.albumId()));
        Assert.notNull(anAlbum, "相册为空，不能编辑");

        anAlbum.changeNameAndDescription(
                changeAlbumCommand.name(),
                changeAlbumCommand.description());
    }

    /**
     * 只删除相册，相册中的照片不同步删除
     *
     * @param deleteAlbumCommand command
     */
    public void delete(DeleteAlbumCommand deleteAlbumCommand) {
        Album deletedAlbum = albumRepository().ofAlbumId(new AlbumId(deleteAlbumCommand.albumId()));

        if (deletedAlbum != null) {
            deletedAlbum.delete();
        }
    }

    private AlbumRepository albumRepository() {
        return albumRepository;
    }
}
